#!/bin/env python
# coding=utf8
import web
import douban.service
from api import APIKEY
from douban.client import OAuthClient
from clcn import get_book_url
from google.appengine.api import memcache as mc
from web.contrib.template import render_mako

apikey = APIKEY

client = douban.service.DoubanService(api_key=apikey)
request_tokens = {}
access_tokens = {}

urls = (
  '/', 'index',
  '/view', 'view'
  #'/view/(.*)', 'view'
)

app = web.application(urls, globals(), autoreload=True)
render = render_mako(
        directories=['templates'],
        input_encoding='utf-8',
        output_encoding='utf-8',
        )


def get_book(username, start_id, max_number = 30):
    uri = "http://api.douban.com/people/%s/collection?cat=book&start-index=%s&max-results=%s&status=wish" %(
            username, start_id, max_number)
    return client.GetCollectionFeed(uri)

def get_all_books(uid, page=1):
    sid = (page-1)*30 + 1
    max = 30
    books = []
    key = '%s:%s' % (str(uid), str(page))
    data = mc.get(key)
    if data:
        return data
    else:
        book = get_book(uid, sid)
        books.append(book)
        table = []
        for b in books:
            for e in b.entry:
                attributes = e.subject.attribute
                for attribute in attributes:
                    if attribute.name == "isbn13":
                        isbn = int(attribute.text)
                        t = get_book_url(isbn)
                        if t:
                            table.append(t)
        mc.set(key, table, 3600*24)
        return table

#get_all_books('jollychang')
def get_all_tables(username, page=1):
    return get_all_books(username, page)
     
#get_isbn("jollychang")
class index:
    def GET(self):
        return render.index()

class view:
    def GET(self):
        i = web.input(username='jollychang', page='1')
        page = int(i.page)
        user = i.username.strip()
        tables = get_all_tables(user, page)
        l = locals()
        l.pop('self')
        return render.view(**l)
#if __name__ == "__main__": app.run()
#app = web.application(urls, globals())
if __name__ == "__main__": app.cgirun()
